<?php
// +----------------------------------------------------------------------
// | 会员常规操作
// +----------------------------------------------------------------------

namespace User\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Libs\ThirdLogin\QQConnect;
use Think\Controller;

class LoginController extends UserbaseController {

    /**
     * 会员登录页显示
     */
    public function index(){
       // $backurl = $_REQUEST['backurl'] ? $_REQUEST['backurl'] : cookie("backurl");
        //判断是不是跳转过来的
        $ifredirect=I('get.t');
        if($ifredirect=='rd'){
            $backurl = cookie("backurl") ? cookie("backurl") : $_REQUEST['backurl'];
        }else{
            cookie('backurl',null);
        }
        if(empty($backurl)){
            $backurl=$_SERVER['HTTP_REFERER'];
        }
    //    cookie("backurl", null);
        if (!empty($this->userid)) {
           // $this->success("您已经是登陆状态！", $backurl ? $backurl : U("/user/index/"));
        	if($backurl)
        	{
        		header("Location:".$backurl);
        	}
        	else
        	{
        		header("Location:".U("Index/index"));
        	}
        } else {
            $this->assign('backurl', $backurl);
            $this->display();
        }
    }


    /**
     * 会员登录
     */
    public function dologin(){
        //用户名
        $loginName = I('request.username', null, 'trim');
        //密码
        $password = I('request.password');
        //下次自动登陆
        $autoLogin = I('request.autoLogin', 0, 'intval');

        //backurl
        $backurl=I('request.username', null, 'trim');

        if(empty($loginName)){
            $this->error('请输入用户名!');
        }
        if(empty($password)){
            $this->error('请输入登录密码!');
        }
        $userid = service('Passport')->loginLocal($loginName, $password, $autoLogin ? 86400 * 180 : 86400);

        if ($userid > 0) {
            $userInfo = service("Passport")->getLocalUser((int) $userid);
            //待审核
            if ($userInfo['islock'] == true) {
                service("Passport")->logoutLocal();
                $this->error('您的帐号已被锁定!');
            }
            if(!empty($backurl)){
                $this->success("登陆成功!",U($backurl));
            }else{
                $this->success("登陆成功!",U('Index/index'));
            }
        } else {
            //登陆失败
            $this->error('您的帐号或密码错误!');
        }

    }


    public function register(){
        $backurl = $_REQUEST['backurl'] ? $_REQUEST['backurl'] : cookie("backurl");
        cookie("backurl", null);
        if (!empty($this->userid)) {
            //$this->success("您已经是登陆状态！", $backurl ? $backurl : U("Index/index"));
            if($backurl)
            {
            	header("Location:".$backurl);
            }
            else 
            {
            	header("Location:".U("Index/index"));
            }
        } else {
            $this->assign('backurl', $backurl);
            $this->display();
        }
    }


    /**
     * 会员注册
     */
    public function doRegister() {

        $post = I('post.');
        //用户名
        $post['uname'] = I('post.uname');

        if(!is_email($post['uname'])){
            $this->error('用户名必须为邮箱!');
        }
        
        $is_user = M('User')->where(array('uname' => $post['uname']))->count();
        if($is_user > 0)
        {
            $this->error("该邮箱已经被注册了");
        }
        
        $post['nickname']  = I('post.nickname');
        //设置密码
        $post['upassword'] = I('post.password');
        $pwd = I('post.password2');
        if (empty($post['upassword'])) {
            $this->error('请输入您的密码！');
        }
        if (false == isMin($post['upassword'], 6)) {
            $this->error('密码不能小于6位！');
        }
        if($post['upassword'] != $pwd)
        {
        	$this->error("两次输入的密码不一致");
        }
        //验证码
        $vCode = I('post.vCode');

        if (false == $this->verify($vCode, 'userregister')) {
            $this->error('验证码错误，请重新输入！');
        }

        $info = $this->userDb->token(false)->create($post);
        if ($info) {
            $userid = service('Passport')->userRegister($info['uname'], $info['upassword']);

            if ($userid > 0) {
                //获取用户信息
                $memberinfo = service("Passport")->getLocalUser((int) $userid);
                $info['uname'] = $memberinfo['uname'];
                $info['upassword'] = $memberinfo['upassword'];
                $info['logtimes']=1;
                $info['login_time']=time();
                $info['lastip']=get_client_ip();
                $info['openuid']=C('BEGIN_UID')+$userid;
                $info['type']='reg';
                $info['islock']=false;
                if(is_email($info['uname'])){
                    $info['uemail']=$info['uname'];
                }elseif(is_mobile($info['uname'])){
                    $info['umobile']=$info['uname'];
                }
                //新注册用户积分
                $info['upoint'] = 0;

                if (false !== $this->userDb->where(array('userid' => $memberinfo['userid']))->save($info)) {
                    //获取积分
                    service('Passport')->userDynamic($memberinfo['userid'],20,'注册获取20个积分',1,'register');
                    //注册登陆状态
                    service("Passport")->loginLocal($post['uname'], $post['upassword']);
                    $this->success("会员注册成功,正转向个人中心！,请完善个人资料", U('Index/index'));
                } else {
                    //删除
                    service("Passport")->userDelete($memberinfo['userid']);
                    $this->error("会员注册失败！");
                }
            } else {
                $this->error(service("Passport")->getError()? : '帐号注册失败！');
            }
        } else {
            $this->error($this->userDb->getError()? : '帐号注册失败！');
        }
    }


    /**
     * 第三方登录完成注册
     */
    public function thirdReg() {
        $post = I('post.');
        $post['uname'] = I('post.uname');
        if(!is_email($post['uname'])){
            $this->error('用户名必须为邮箱!');
        }
        
        $is_user = M('User')->where(array('uname' => $post['uname']))->count();
        if($is_user > 0)
        {
            $this->error("该邮箱已经被注册了");
        }
        $post['nickname']  = I('post.nickname');
        $post['upassword'] = I('post.password');
        if (empty($post['upassword'])) {
            $this->error('请输入您的密码！');
        }
        if (false == isMin($post['upassword'], 6)) {
            $this->error('密码不能小于6位！');
        }
        
        $pwd = I('post.password2');
        if($post['upassword'] != $pwd)
        {
            $this->error("两次输入的密码不一致");
        }
        $info = $this->userDb->token(false)->create($post);
        if ($info) {
            $userid = service('Passport')->userRegister($info['uname'], $info['upassword']);
            if ($userid > 0) {
                //获取用户信息
                $memberinfo = service("Passport")->getLocalUser((int) $userid);
                $info['uname'] = $memberinfo['uname'];
                $info['upassword'] = $memberinfo['upassword'];
                $info['logtimes']=1;
                $info['login_time']=time();
                $info['lastip']=get_client_ip();
                $info['openkey']=$post['openkey'];
                $info['openuid']=C('BEGIN_UID')+$userid;
                $info['type']=$post['type'];
                $info['islock']=false;
                if(is_email($info['uname'])){
                    $info['uemail']=$info['uname'];
                }elseif(is_mobile($info['uname'])){
                    $info['umobile']=$info['uname'];
                }

                //保存为本地头像
                /*$uploadPath='f/user/'.date('y').'/'.date('m').'/'.date('d');
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath,0777,true);
                }
                $img = file_get_contents($post['uavatar']);
                $fileName =  'uavatar_'.$memberinfo['userid'] .'.jpg';
                $file =  $uploadPath.'/' . $fileName;
                file_put_contents($file, $img);

                $info['uavatar']='/'.$file;*/

                //新注册用户积分
                $info['upoint'] = 0;


                if (false !== $this->userDb->where(array('userid' => $memberinfo['userid']))->save($info)) {
                    //获取积分
                    service('Passport')->userDynamic($this->userid,20,'注册获取20个积分',1,'register');
                    
                    //注册登陆状态
                    service("Passport")->loginLocal($post['uname'], $post['upassword']);
                    $this->success("登录成功,正转向个人中心！", U('Index/index'));
                } else {
                    //删除
                    service("Passport")->userDelete($memberinfo['userid']);
                    $this->error("登录失败！");
                }
            } else {
                $this->error(service("Passport")->getError()? : '登录失败！');
            }
        } else {
            $this->error($this->userDb->getError()? : '登录失败！');
        }
    }


    //第三方登录地址
    public function login($type = null){
        empty($type) && $this->error('参数错误');

        //加载ThinkOauth类并实例化一个对象
     //   import("Libs.ThirdLogin.ThinkOauth");
        $sns  = \Libs\ThirdLogin\ThinkOauth::getInstance($type);

        //跳转到授权页面
        redirect($sns->getRequestCodeURL());
    }

    //授权回调地址
    public function callback($type = null, $code = null){
        (empty($type) || empty($code)) && $this->error('参数错误');

        //加载ThinkOauth类并实例化一个对象
    //    import("Libs.ThirdLogin.ThinkOauth");
        $sns  =  \Libs\ThirdLogin\ThinkOauth::getInstance($type);

        $extend = null;
        //请妥善保管这里获取到的Token信息，方便以后API调用
        //调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
        //如： $qq = ThinkOauth::getInstance('qq', $token);
        $token = $sns->getAccessToken($code , $extend);
        //获取当前登录用户信息
        if(is_array($token)){
            $user_info = \Libs\ThirdLogin\TypeEvent::$type($token);
            $user=M('User')->field('userid,uname')->where(array('openkey'=>$user_info['openkey']))->find();
            if(!empty($user)){
                service("Passport")->registerLogin($user);
                $this->success("登录成功,正转向个人中心！", U('index/index'));
            }else{
                $this->assign('userinfo',$user_info);
                $this->assign('token',$token);
                $this->display();
            }
        }
    }
    
    /**
     * 忘记密码
     */
    public function forget()
    {
    	if($_POST)
    	{
    		if($this->userid)
    		{
    			$this->error("你已经登录了", '/');
    		}
    		$post = I('post.');
    		
    		if(empty($post['uname']))
    		{
    			$this->error("请输入你的注册邮箱");
    		}
    		if(!is_email($post['uname']))
    		{
    			$this->error("请输入正确的邮箱格式");
    		}
    		$user = M('User')->where(array('uname' => $post['uname']))->field("uemail, userid")->find();
    		if(!$user['userid'])
    		{
    			$this->error("你输入注册邮箱不存在");
    		}
    		
    		$is_exist = M('UserRelog')->where(array('userid' => $user['userid']))->count();
    		if($is_exist > 0)
    		{
    			$info['vcode'] = genRandomString(6);
    			$info['create_time'] = time();
    			$id = M('UserRelog')->where(array('userid' => $user['userid']))->save($info);
    		}
    		else 
    		{
    			$info['userid'] = $user['userid'];
    			$info['vcode'] = genRandomString(6);
    			$info['create_time'] = time();
    			$id = M('UserRelog')->add($info);
    		}
    		//SendMail($address, $title, $message);
    		if($id)
    		{
    			$address = $post['uname'];
    			$title = "修改密码";
    			$url = "http://".$_SERVER['HTTP_HOST']."/user/login/repwd?userid=".$user['userid']."&vcode=".$info['vcode'];
    			$message = "欢迎使用烘焙圈，点击<a href='$url' target='_blank'>修改密码</a>，链接有效期为3天";
    			if(SendMail($address, $title, $message))
    			{
    				$this->success("邮件发送成功,请在3天内修改密码", "/");
    			}
    			else
    			{
    				$this->error("邮件发送失败");
    			}
    		}
    		else
    		{
    			$this->error("系统繁忙");
    		}
    	}
    	else
    	{
    		$this->display();
    	}
    }
    /**
     * 修改密码
     */
    public function repwd()
    {
    	if($_POST)
    	{
    		$post = I('post.');
    		//print_r($post);
    		$is_exist = M('UserRelog')->where(array('userid' => $post['userid'], 'vcode' => $post['vcode']))->count();
    		if($is_exist == 0)
    		{
    			$this->error("标识vcode错误", "/");
    		}
    		
    		if(empty($post['newpwd']))
    		{
    			$this->error("请输入新密码");
    		}
    		if(empty($post['newpwd2']))
    		{
    			$this->error("请输入确认密码");
    		}
    		if(hy_strlen($post['newpwd']) < 6)
    		{
    			$this->error("输入的密码不能小于6个字符");
    		}
    		if($post['newpwd'] != $post['newpwd'])
    		{
    			$this->error("输入的两次密码不一致");
    		}
    		//$user = M('User')->where(array('userid' => $post['userid']))->field("authkey")->find();
    		$res = D('User/User')->ChangePassword($post['uname'], $post['newpwd']);
    		if($res)
    		{
    			$this->success("修改成功", "/");
    		}
    		else
    		{
    			$this->error("修改失败");
    		}
    	}
    	else 
    	{
    		if($this->userid)
    		{
    			$this->error("你已经登录了", "/");
    		}
	    	$info = I('get.');
	    	$data = M('UserRelog')->where(array('userid' => $info['userid']))->find();
	    	$now_time = time() - 3 * 24 * 60 * 60;
	    	
	    	if($data['create_time'] < $now_time)
	    	{
	    		$this->error("该链接已经失效", "/");
	    	}
	    	
	    	if($data['vcode'] != $info['vcode'])
	    	{
	    		$this->error("标识vcode不正确", "/");
	    	}
	    	
	    	$uname = M('User')->where(array('userid' => $info['userid']))->getField("uname");
	    	
	    	$this->assign("uname", $uname);
	    	$this->assign("info", $info);
	    	$this->display();
    	}
    }

}